package sagroup.pdlime;

import java.net.UnknownHostException;


import lights.adapters.Field;
import lights.adapters.Tuple;
import lime2.Launcher;
import lime2.LimeServer;
import lime2.PolicyException;

public class NodePartinTesting {

	private LimeServer server;

	PiccoTVRLimeTupleSpace piccoSpace;

	public NodePartinTesting(int port, int httpPort)
			throws UnknownHostException, PolicyException {
		server = LimeServer.getServer();
		if (!server.isBooted()) {
			// if the user did not choose any tuplespace factory then we use the
			// default tuplespace factory
			String tsfactory = "lights.adapters.builtin.TupleSpaceFactory";

			// starts server
			Launcher.launch("-start -port " + port + " -http " + httpPort
					+ " -tsfactory " + tsfactory);
			System.out.println("--- open http://localhost:" + httpPort
					+ "/ with your browser ---\n");

			// server.boot();
		}

		// when we testing, we only use one tupleSpace named "share" and maybe 3
		// nodes.
		piccoSpace = PiccoTVRLimeTupleSpace.get("share");
	}

	static String FRPrefix = "tsToBeFR";
	static String RCPrefix = "tsToBeRC";
	// 2 is ok, if more we must page down and up the html which is bad.
	static int totalToBeOut = 2;

	public static void main(String[] args) throws UnknownHostException,
			PolicyException {
		// deal with parameters
		if (args.length != 2) {
			System.out.println("must has parameters like:1973 8073");
			System.exit(0);
		}
		final int PORT = Integer.valueOf(args[0]);
		final int HTTP_PORT = Integer.valueOf(args[1]);
		NodePartinTesting srcNode = new NodePartinTesting(PORT, HTTP_PORT);

		srcNode.piccoSpace.changeReplicationPolicy(new TupleType(FRPrefix),
				PDPolicy.FR);
		srcNode.piccoSpace.changeUpdatePolicy(new TupleType(FRPrefix),
				PDPolicy.MASTER);
		srcNode.piccoSpace.changeReplicationPolicy(new TupleType(RCPrefix),
				PDPolicy.RC);
		srcNode.piccoSpace.changeUpdatePolicy(new TupleType(RCPrefix),
				PDPolicy.MASTER);

		for (int i = 0; i < totalToBeOut; i++) {
			srcNode.piccoSpace.out(new TupleType(FRPrefix), new Tuple()
					.add(new Field().setValue(FRPrefix + PORT + i)));
		}

		for (int i = 0; i < totalToBeOut; i++) {
			srcNode.piccoSpace.out(new TupleType(RCPrefix), new Tuple()
					.add(new Field().setValue(RCPrefix + PORT + i)));
		}

	}

}
